package me.flyray.biz.thymeleaf.modules.wechat.biz;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.AuthUtil;

import net.sf.json.JSONObject;

@Service
public class WechatBiz {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(WechatBiz.class);

	/**
	 * 获取微信用户信息
	 * @param request
	 * @return
	 */
	public Map<String, Object> getWechatUserInfo(@RequestBody Map<String, Object> params){
		Map<String, Object> respMap = new HashMap<String, Object>();
		logger.info("微信获取用户信息请求参数。。。。。。。{}", params);
		String code = (String) params.get("code");
		String goodsId = (String) params.get("goodsId");
		String goodsPic = (String) params.get("goodsPic");
		String goodsPrice = (String) params.get("goodsPrice");
		String platformId = (String) params.get("platformId");
		String merchantId = (String) params.get("merchantId");
		String openid = null;
		String nickname = null;
		try {
			String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + "wx6225d2d623ff1b40" +
					"&secret=" + "548bc84204dba0e8abd6402dbb04f2a2" +
					"&code=" + code +
					"&grant_type=authorization_code";
			JSONObject jsonObject = AuthUtil.doGetJson(url);
			openid=jsonObject.getString("openid");
			String token=jsonObject.getString("access_token");
			String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token=" + token +
					"&openid=" + openid +
					"&lang=zh_CN";
			JSONObject userInfo=AuthUtil.doGetJson(infoUrl);
			nickname=userInfo.getString("nickname");

			try{
				nickname = java.net.URLEncoder.encode(nickname,"UTF-8");
			}catch(Exception ex){
				ex.printStackTrace();
			}
			respMap.put("openid", openid);
			respMap.put("nickname", nickname);
			respMap.put("goodsId", goodsId);
			respMap.put("goodsPic", goodsPic);
			respMap.put("goodsPrice", goodsPrice);
			respMap.put("platformId", platformId);
			respMap.put("merchantId", merchantId);
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			respMap.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			respMap.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
		}

		return respMap;
	}

}
